<template>
  <div class="pledge">
    <!-- 标题 -->
    <div class="mb-15">
      <div class="flex flex-rc fz-40 fw-bold ls">{{ $t('认购收益') }}</div>
      <div class="flex flex-rc fz-20">{{ $t('每日奖励') }}：4%</div>
    </div>

    <!-- 认购收益 -->
    <div class="container">
      <!-- 可用余额 -->
      <div class="mb-15">
        <div class="cl-second">{{ $t('可用余额') }}</div>
        <div class="fz-20 fw-bold">{{ balance }} $CTIN</div>
      </div>

      <!-- 认购收益金额 -->
      <div class="mb-40">
        <!-- 金额 -->
        <div class="mb-15">
          <div class="cl-second mb-5">{{ $t('输入认购单位') }}：</div>

          <van-field
            class="mb-10"
            style="font-size: 20px"
            type="number"
            :border="false"
            :placeholder="$t('输入数量')"
            v-model="num"
          ></van-field>

          <van-button
            v-for="(v, i) in [1, 50, 100, 500, 1000]"
            style="width: 40px; height: 20px"
            type="primary"
            size="mini"
            plain
            :key="i"
            @click="num = v"
          >
            {{ v }}
          </van-button>
        </div>
      </div>

      <van-button
        style="height: 45px"
        color="linear-gradient(to right, #0eb78e, #4573a4, #7735b8)"
        block
        @click="pledge"
      >
        <div class="fz-17 cl-black fw-bold ls">{{ $t('确定') }}</div>
      </van-button>
    </div>
  </div>
</template>

<script setup>
import { ref, inject } from 'vue'
import {
  showToast,
  showSuccess,
  showError,
  showLoading,
  toNumber,
  toBigNumber,
} from 'js/utils'

const num = ref('')
const amount = ref('')
const balance = inject('balance')
const loading = ref(null)

// 认购收益
async function pledge() {
  try {
    if (!num.value) {
      return showToast($t('输入认购单位'))
    }

    amount.value = num.value * 98
    loading.value = showLoading()

    // 判断用户Ctin授权给Order的额度是否足够，不够就先授权额度
    const authorizedBalanceByCtin = await getAuthorizedBalanceByCtin()

    if (authorizedBalanceByCtin <= 0) {
      // 需要授权额度
      await authorizeBalanceByCtin()
    } else if (authorizedBalanceByCtin < amount.value) {
      // 可用额度小于用户投资的金额
      await authorizeBalanceByCtin()
    }

    // 投资金额
    await investAmount()

    loading.value?.close()
  } catch (err) {
    console.error(err)
    loading.value?.close()
  }
}

// 投资金额
function investAmount() {
  return new Promise(async (resolve, reject) => {
    try {
      console.log(`投资金额：${amount.value}`)
      const res = await orderContract.context.methods
        .invest(toBigNumber(amount.value))
        .send({
          from: fromAddress,
        })
      amount.value = ''
      showSuccess($t('认购收益成功'))
      console.log('认购收益成功')
      console.log(res)
      resolve(res)
    } catch (err) {
      amount.value = ''
      showError($t('认购收益失败'))
      console.error('认购收益失败')
      console.error(err)
      reject(err)
    }
  })
}

// Ctin授权Order额度
function authorizeBalanceByCtin() {
  return new Promise(async (resolve, reject) => {
    try {
      const quota = toBigNumber(50000000) // 授权 50000000 Ctin额度
      const res = await usdtContract.context.methods
        .approve(orderContract.context._address, quota)
        .send({
          from: fromAddress,
        })
      showSuccess($t('授权Ctin余额成功'))
      console.log(`授权Ctin余额成功：${toNumber(quota)}`)
      resolve(quota)
    } catch (err) {
      showError($t('授权Ctin余额失败'))
      console.error('授权Ctin余额失败')
      console.error(err)
      reject(err)
    }
  })
}

// 获取Ctin授权给Order的额度
function getAuthorizedBalanceByCtin() {
  return new Promise(async (resolve, reject) => {
    try {
      const authorizedBalance = await usdtContract.context.methods
        .allowance(fromAddress, orderContract.context._address)
        .call()
      const authorizedBalanceInBigNumber = Number(toNumber(authorizedBalance))
      console.log(`获取Ctin授权余额成功：${authorizedBalanceInBigNumber}`)
      resolve(authorizedBalanceInBigNumber)
    } catch (err) {
      showError($t('获取Ctin授权余额失败'))
      console.error('获取Ctin授权余额失败')
      console.error(err)
      reject(err)
    }
  })
}
</script>

<style lang="scss" scoped>
.container {
  border-radius: 20px;
  background: url('../assets/img/plegde/box_1.png') no-repeat left top / 100%;
  overflow: hidden;
}
</style>
